/*
 * LongType.java
 *
 * Created on July 31, 2007, 7:35 PM
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package tal.drivechain.variable.types;

/**
 * A DataType class that handles long integer numbers.
 * Name: "long"
 * Value object: Long
 * Value range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (64bit)
 * Type code: 5
 * Syntax: long:<any whole number>
 * Can cast from Integer, Double or Boolean.
 *
 * @author Tal Eisenberg
 */
public final class LongType extends NumberType{
    
    /** Creates a new instance of LongType */
    public LongType() {
        super("long", Long.class, 5);
    }

    public Object parseNumber(Number value) throws IllegalArgumentException {
        try {
            if (value.longValue()==value.doubleValue())
                return new Long(value.longValue());
            else throw new IllegalArgumentException("Invalid long value: " + value);
        } catch (NumberFormatException ne) {
            throw new IllegalArgumentException("Invalid long value: " + value);
        }
    }

    @Override
    public Object cast(Object value) throws IllegalArgumentException {
        try {
            return super.cast(value);
        } catch (IllegalArgumentException e) {
            if (value instanceof Integer) return ((Integer)value).longValue();
            else if (value instanceof Double) return (long)Math.round((Double)value);
            else if (value instanceof Float) return  (long)Math.round((Float)value);
            else if (value instanceof Boolean) return (long)((Boolean)value==true?1:0);
            else throw new IllegalArgumentException("Can't cast " + value + " to a long value.");
        }
    }

}
